package com.leinao.job.controller;

import com.alibaba.fastjson.JSON;
import com.leinao.commons.Response;
import com.leinao.constant.Constant;
import com.leinao.constant.LoginEnum;
import com.leinao.constant.ProjectErrorEnum;
import com.leinao.constant.ProjectJobHandleEnum;
import com.leinao.job.model.PaiProjectJob;
import com.leinao.job.service.JobService;
import com.leinao.login.dto.LoginResultDto;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 任务
 * 
 * @author wangshoufa
 * @date 2018年11月8日 下午2:49:38
 *
 */

@RestController
@CrossOrigin
public class JobController {

	private static Logger logger = LoggerFactory.getLogger(JobController.class);

	@Autowired
	private JobService jobService;

	/**
	 * 若项目下有任务调用该接口
	 * 
	 * @param request req请求
	 * @param paiProjectJob 请求数据
	 * @return 返回任务结果
	 * @author wangshoufa
	 * @date 2019年3月13日
	 *
	 */
	@ApiOperation(value = "新建任务", notes = "新建任务")
	@PostMapping(value = "/createJob")
	@ApiImplicitParam(name = "paiProjectJob", value = "paiProjectJob", required = true, dataType = "PaiProjectJobDto")
	public Response<String> createJob(HttpServletRequest request, @RequestBody PaiProjectJob paiProjectJob) {
		logger.info("createJob paiProjectJob： {}", paiProjectJob);
		String obj = (String) request.getSession().getAttribute("userInfo");
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		// 1.0 验证用户有效性
		if (userInfo == null && StringUtils.isBlank(userInfo.getUserId())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, LoginEnum.LOGIN_TIMEOUT.getSeq(), LoginEnum.LOGIN_TIMEOUT.getDesc(), null);
		}
		// 1.1 任务类型不能为空，项目id不能为空，项目名称不能为空
		if (paiProjectJob.getJobType() == null || paiProjectJob.getJobType().compareTo(0) <= 0 || paiProjectJob.getProjectId() == null
				|| StringUtils.isBlank(paiProjectJob.getProjectName())) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ProjectErrorEnum.PARAM_ERROR.getSeq(), ProjectErrorEnum.PARAM_ERROR.getDesc(),
					null);
		}
		// 1.2 任务配置信息不能为空，且任务配置config必须是字符串
		if(StringUtils.isBlank(paiProjectJob.getConfig()) || !(paiProjectJob.getConfig() instanceof String)) {
			return Response.ok(Constant.RESPONSE_STATUS_SUCCESS, ProjectErrorEnum.PARAM_FORMAT_ERROR.getSeq(), ProjectErrorEnum.PARAM_FORMAT_ERROR.getDesc(), null);
		}
		return jobService.createJob(paiProjectJob, userInfo);
	}
    /**
     * @description 任务操作
     * @param request
     * @param jobId 任务ID
     * @param operateType 1.查看 2.停止或取消
     * @return
     * @author wangshoufa
	 * @date 2019年3月13日
     */
	@ApiOperation(value = "任务操作", notes = "任务操作")
	@PostMapping(value = "/jobOperation")
	public Response<Object> jobOperation(HttpServletRequest request,
										 @ApiParam(value = "任务名", required = true) @RequestParam Long jobId,
										 @ApiParam(value = "1：查看，2：停止或者取消", required = true) @RequestParam Integer operateType) {
		logger.info("jobOperation jobId： {},operateType: {}", jobId, operateType);
		String obj = (String) request.getSession().getAttribute("userInfo");
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		return jobService.jobOperation(jobId, operateType, userInfo.getToken());
	}
	
	/**
	 * @description 任务调式
	 * @param projectId  任务id
	 * @return
	 * @author wangshoufa
	 * @date 2019年3月13日
	 */
	@ApiOperation(value = "获取jobJupyterUrl", notes = "get jobJupyterUrl")
	@GetMapping(value = "/jobJupyterUrl")
	public Response<String> jobJupyterUrl(@ApiParam(value = "项目Id", required = true) @RequestParam Integer projectId, HttpServletRequest request) {
		logger.info("jobJupyterUrl projectId: {}", projectId);
		String obj = (String) request.getSession().getAttribute("userInfo");
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);
		return jobService.jobJupyterUrl(projectId, userInfo.getToken());
	}

	/**
	 * 功能描述：编辑任务备注
	 * @param request req请求
	 * @param projectId 项目id
	 * @param jobName 任务名称
	 * @param remark 任务备注
	 * @return com.leinao.commons.Response<java.lang.String>  返回编辑结果
	 * @Author: guoliangbo
	 * @Date: 2019/5/17 16:49
	 */
	@ApiOperation(value = "编辑任务备注", notes = "任务详情页-任务备注")
	@PostMapping(value = "/jobRemarkEdit")
	public Response<String> jobRemarkEdit(HttpServletRequest request,
										  @ApiParam(value = "项目Id", required = true) @RequestParam Integer projectId,
										  @ApiParam(value = "任务Id", required = true) @RequestParam String jobName,
										  @ApiParam(value = "任务备注", required = true) @RequestParam String remark){
		logger.info("jobRemarkEdit projectId: {},jobId: {},remark: {}", projectId, jobName,remark);
		//判断备注长度，不可超过500字符
		if (StringUtils.isNotBlank(remark) && remark.length() > Constant.JOB_REMART_MAX_LENGTH) {
			return Response.error(Constant.RESPONSE_STATUS_SUCCESS, ProjectJobHandleEnum.JOB_REMARK_TOO_LENGTH.getSeq(), ProjectJobHandleEnum.JOB_REMARK_TOO_LENGTH.getDesc(),
					"任务备注太长，不能超过500！");
		}
		String obj = (String) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
		LoginResultDto userInfo = JSON.parseObject(obj, LoginResultDto.class);

		return jobService.jobRemarkEdit(projectId, jobName, remark, userInfo.getUserId());
	}
}
